package com.gogowan.agroenterprise.utils;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

import com.gogowan.agroenterprise.model.AddressInfo;
import com.gogowan.agroenterprise.model.LoginResultInfo;
import com.gogowan.agroenterprise.model.Message;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.WindowManager;
import android.widget.Toast;

/**
 * @Description:基类
 * @author mdp
 * @date 2017年1月3日 上午11:02:42
 */
public class PalUtils {

	public static final boolean DEBUG = false;// 待改
	public static final boolean ENCRYPT = true;// 待改

	public static final String PACK_CODE_ITT = "PACK_CODE_ITT";
	public static final String PACK_TYPE_ITT = "PACK_TYPE_ITT";
	public static final String PACK_MODEL_ITT = "PACK_MODEL_ITT";

	public class MsgType {

		// 装箱
		/** 扫描箱码 */
		public static final int BoxCode = 13000;
		/** 连续扫描产品码装箱 */
		public static final int ScanMaSingleCode = 13002;
		/** 扫描产品码码段装箱 */
		public static final int ScanMaCode = 13001;
		/** 装箱 */
		public static final int AddBoxCode = 13003;

		// 装盒
		/** 扫描产品码当做盒码 */
		public static final int PackCode = 13100;
		/** 连续扫描产品码装盒 */
		public static final int ScanPackMaSingleCode = 13102;
		/** 扫描产品码码段装盒 */
		public static final int ScanPackMaCode = 13101;
		/** 装盒 */
		public static final int AddPackCode = 13103;
		// 装垛
		/** 扫描垛位码 */
		public static final int CribCode = 24000;
		/** 连续扫描产品码、箱码、盒码装垛 */
		public static final int ScanCribMaSingleCode = 26000;
		/** 扫描产品码码段装垛 */
		public static final int ScanCribMaCode = 25000;
		/** 装垛提交 */
		public static final int AddCribCode = 27000;

		// 历史记录
		/** 查询装箱装盒历史记录 */
		public static final int HistoryRecords = 16000;
		/** 装箱/盒查询详细信息 */
		public static final int RecordsDetail = 16100;
		/** 拆箱/拆盒 */
		public static final int SplitBox = 17000;
		/** 拆箱/拆盒扫码 */
		public static final int SplitBoxGetCode = 23000;
		/** 拆垛 */
		public static final int SplitCribCode = 28000;
		/** 确认拆垛协议 */
		public static final int ConfirmSplitCribCode = 29000;

		// 经销商
		/** 获取经销商列表 */
		public static final int GetDealer = 14000;
		/** 删除经销商 */
		public static final int DelDealer = 14300;
		/** 获取经销商详情 */
		public static final int GetDealerInfo = 14400;
		/** 获取地址列表 */
		public static final int GetAreaInfo = 14500;
		/** 新增经销商 */
		public static final int AddDealer = 14100;
		/** 修改经销商 */
		public static final int EditDealer = 14200;
		/** 删除经销商 */
		public static final int DeleteDealer = 14300;
	}

	/**
	 * 获取地域分类
	 *
	 * @param addressList
	 * @param parentID
	 * @return
	 */
	public static List<AddressInfo> getAddressInfoList(List<AddressInfo> addressList, long parentID, int level) {
		List<AddressInfo> reAddressList = new ArrayList<>();
		for (AddressInfo addressInfo : addressList) {
			if (addressInfo.getAddress_ID_Parent() == parentID && addressInfo.getAddressLevel() == level) {
				reAddressList.add(addressInfo);
			}
		}
		if (reAddressList.size() == 0) {
			// PalUtils.showLogE("parentID------>" + parentID +
			// "======level------>" + level);
			for (AddressInfo addressInfo : addressList) {
				if (addressInfo.getAddress_ID() == parentID) {
					reAddressList.add(addressInfo);
					return reAddressList;
				}
			}
		}
		return reAddressList;
	}

	/**
	 * 获取登录信息
	 */
	public static LoginResultInfo getLoginResultInfo(Context context) {
		SharedPreferences prefs = context.getSharedPreferences("LoginINfo", Context.MODE_PRIVATE);
		String content = prefs.getString("saveLoginInfo", "");
		if (isEmpty(content)) {
			return null;
		}
		try {
			return (LoginResultInfo) Utils.fromJSON(content, LoginResultInfo.class);
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 响应中继
	 * 
	 * @param response
	 *            返回内容
	 *
	 * @return 消息内容
	 */
	public static Object getPostResult(String response, Class clazz) {
		Message message = (Message) Utils.fromJSON((String) response, Message.class);
		if (message == null) {
			return null;
		}
		String content = Utils.getMessageContent(message);
		showLogE("response content", content);
		try {
			return Utils.fromJSON(content, clazz);
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 响应中继
	 *
	 * @param response
	 *            返回内容
	 *
	 * @return 消息内容
	 */
	public static Object getDataByTypeResult(String response, Type clazz) {
		Message message = (Message) Utils.fromJSON(response, Message.class);
		if (message == null) {
			return null;
		}
		String content = Utils.getMessageContent(message);
		showLogE("response content", content);
		try {
			return Utils.fromJSON(content, clazz);
		} catch (Exception e) {
			return null;
		}
	}
	/**
	 * 汉字转拼音
	 */
	public static String getPinYin(String strs) {
		HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
		format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
		char[] ch = strs.trim().toCharArray();
		StringBuffer buffer = new StringBuffer("");
		try {
			for (int i = 0; i < ch.length; i++) {
				if (Character.toString(ch[i]).matches("[\u4e00-\u9fa5]+")) {
					String[] temp = PinyinHelper.toHanyuPinyinStringArray(ch[i], format);
					if (temp == null || temp.length == 0) {
						return "";
					}
					buffer.append(temp[0]);
					buffer.append(" ");
				} else {
					buffer.append(Character.toString(ch[i]));
				}
			}
		} catch (BadHanyuPinyinOutputFormatCombination e) {
			e.printStackTrace();
		}
		return buffer.toString();
	}

	/**
	 * 拨号 uses-permission android:name="android.permission.CALL_PHONE"
	 *
	 * @param phone
	 * @param isDirect
	 *            是否直接拨号
	 */
	public static Intent getCallIntent(String phone, boolean isDirect) {
		Intent intent = new Intent(isDirect ? Intent.ACTION_CALL : Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
		return intent;
	}

	public static boolean matchesRegex(String regex, String inputValue) {
		// matches()对整个字符串进行匹配,只有整个字符串都匹配了才返回true
		return Pattern.compile(regex).matcher(inputValue).matches();
	}

	/**
	 * 获取DisplayMetrics对象
	 *
	 * @param context
	 * @return
	 */
	public static DisplayMetrics getDisplayMetrics(Context context) {
		WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		DisplayMetrics displayMetrics = new DisplayMetrics();
		windowManager.getDefaultDisplay().getMetrics(displayMetrics);
		return displayMetrics;
	}

	/**
	 * 获取系统dp尺寸密度值
	 *
	 * @param context
	 *            应用程序上下文
	 * @return
	 */
	public static float getDensity(Context context) {
		return getDisplayMetrics(context).density;
	}

	/**
	 * dip转换为px大小
	 *
	 * @param context
	 *            应用程序上下文
	 * @param dpValue
	 *            dp值
	 * @return 转换后的px值
	 */
	public static int dp2px(Context context, int dpValue) {
		return (int) (dpValue * getDensity(context) + 0.5f);
	}

	/**
	 * px转换为dp值
	 *
	 * @param context
	 *            应用程序上下文
	 * @param pxValue
	 *            px值
	 * @return 转换后的dp值
	 */
	public static int px2dp(Context context, int pxValue) {
		return (int) (pxValue / getDensity(context) + 0.5f);
	}

	public static void showLogE(String msg) {
		showLogE("DEBUG_LOG_E------>", msg);
	}

	public static void showLogE(String tag, String msg) {
		if (!DEBUG) {
			return;
		}
		Log.e(tag, msg);
	}

	public static void showShortToast(Context context, String msg) {
		Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 是否无内容
	 */
	public static boolean isEmpty(String str) {
		return str == null || str.trim().length() == 0;
	}

	/**
	 * 是否无内容
	 */
	public static boolean isEmpty(Collection<?> collection) {
		return collection == null || collection.size() == 0;
	}

	public static final String REGEX_TEL = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$";
	public static final String REGEX_MOBILE = "^((13[0-9])|(15[^4,\\D])|(18[0-9])|(17[0-9])|(14[0-9]))\\d{8}$";

	/**
	 * 是否无内容
	 * 
	 * @param context
	 *            Application
	 * @param str
	 * @param toast
	 */
	public static boolean checkEmpty(Context context, String str, String toast) {
		if (PalUtils.isEmpty(str)) {
			PalUtils.showShortToast(context, toast);
			return true;
		}
		return false;
	}

	private static long lastClickTime = 0;

	/**
	 * 连击初步判断
	 */
	public static boolean isDClick() {
		long time = System.currentTimeMillis();
		long timeD = time - lastClickTime;
		if (0 < timeD && timeD < 300) {
			return true;
		}
		lastClickTime = time;
		return false;
	}

}
